package com.alinesno.cloud.base.logger.alarm;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alinesno.cloud.base.logger.alarm.constants.AlarmTypeConstants;
import com.alinesno.cloud.base.logger.entity.LogTriggerConditionEntity;
import com.alinesno.cloud.base.logger.entity.LogTriggerEntity;
import com.alinesno.cloud.base.logger.service.ILogTriggerConditionService;
import com.alinesno.cloud.base.logger.service.ILogTriggerService;
import com.alinesno.cloud.base.notice.entity.EmailSendEntity;
import com.alinesno.cloud.base.notice.entity.SmsSendEntity;
import com.alinesno.cloud.base.notice.enums.NoticeSendTypeEnum;
import com.alinesno.cloud.base.notice.service.INoticeSendService;
import com.alinesno.cloud.common.facade.wrapper.Condition;
import com.alinesno.cloud.common.facade.wrapper.RestWrapper;

import cn.hutool.core.date.DateTime;

/**
 * 通知服务
 * 
 * @author WeiXiaoJin
 * @since 2020年1月29日 下午19:45:08
 */
public abstract class AlarmService {

	protected static final Logger log = LoggerFactory.getLogger(AlarmService.class);

	protected static final int EMAIL_ERROR_DEFAULT_LENGTH = 2 ; 
	
	protected static final String NR = "<br/>";
	
	protected List<LogTriggerConditionEntity> cs = null ; 
	
	@Autowired
	private INoticeSendService noticeService;
	
	@Autowired
	private ILogTriggerService triggerService ; 

	@Autowired
	private ILogTriggerConditionService conditionService;

	/**
	 * 发送通知
	 * 
	 * @param e
	 * @throws Exception
	 */
	public void alarm(LogTriggerEntity e) throws Exception {
		
		if(e.getHasRunTime() == e.getContinueTime()) {
			log.warn("任务{}，执行次数{}已经到，不再执行" , e.getTriggerName() , e.getHasRunTime());
			return ; 
		}
	
		// >>>>>>>>>>>>>>>> 判断是否达到运行时间_start >>>>>>>>>>>>>>>>>>>
		long now = DateTime.now().getTime();
		Date endTime = e.getEndTime();
		if (endTime != null) {
			if (DateTime.of(endTime).getTime() - now < 0) {
				return;
			}
		}

		Date startTime = e.getStartTime();
		if (startTime != null) {
			if (DateTime.of(startTime).getTime() - now > 0) {
				return;
			}
		}
		// >>>>>>>>>>>>>>>> 判断是否达到运行时间_end >>>>>>>>>>>>>>>>>>>

		// 查询条件
		RestWrapper restWrapper = RestWrapper.create().eq("triggerId",
				e.getId());
		List<LogTriggerConditionEntity> cList = conditionService.findAll(restWrapper);

		if (cList == null || cList.size() == 0) {
			return;
		}

		boolean isAlarm = this.doAlarm(e, cList);
		if (isAlarm) { // 如果达到通知条件，则进行通知
			if(StringUtils.isNoneBlank(e.getTriggerType())) {
				String alarmType[] = e.getTriggerType().split(",");
				for (String t : alarmType) {
					switch (t) {
					case AlarmTypeConstants.NOTICE_EMAIL:
						EmailSendEntity email = generatorEmail(e);
						noticeService.sendHtmlEmail(email, NoticeSendTypeEnum.NOTICE_EMAIL_163);
						break;
					case AlarmTypeConstants.NOTICE_SMS:
						SmsSendEntity sms = generatorSms(e);
						noticeService.sendSms(sms, NoticeSendTypeEnum.NOTICE_SMS_ALIYUN);
						break;
					default:
						break;
					}
				}
				e.setHasRunTime((e.getHasRunTime()==null?0:e.getHasRunTime())+1);
				triggerService.save(e) ; 
			}
		}

	};

	/**
	 * 构建过滤器
	 * @param cList
	 * @return
	 */
	protected RestWrapper buildFilterCondition(List<LogTriggerConditionEntity> cList) {
		RestWrapper restWrapper = RestWrapper.create();
		List<Condition> ls = new ArrayList<Condition>();

		for (LogTriggerConditionEntity c : cList) {
			Condition condition = new Condition(c.getConditionSpel(), c.getConditionName(), c.getConditionValue());
			ls.add(condition);
		}
		
		restWrapper.setCondition(ls) ; 
		return restWrapper ; 
	}

	/**
	 * 触发通知事件
	 * 
	 * @param e
	 * @param cList
	 * @return
	 */
	public abstract boolean doAlarm(LogTriggerEntity e, List<LogTriggerConditionEntity> cList);

	/**
	 * 生成Email
	 * 
	 * @param e
	 * @return
	 */
	protected abstract EmailSendEntity generatorEmail(LogTriggerEntity e);

	/**
	 * 生成Sms
	 * 
	 * @param e
	 * @return
	 */
	protected abstract SmsSendEntity generatorSms(LogTriggerEntity e);

	/**
	 * 生成wechat
	 * 
	 * @param e
	 */
	protected abstract void generatorWechat(LogTriggerEntity e);

	/**
	 * 生成dingtalk
	 * 
	 * @param e
	 */
	protected abstract void generatorDingtalk(LogTriggerEntity e);

}
